package com.ygqh.baby.service.wechat.api;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.NameFilter;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.mp.api.MenuApi;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.type.ButtonType;
import com.ygqh.baby.model.wx.WxButton;

public class YgMenuApi extends MenuApi {
	private final TokenHolder ygTokenHolder;

	public YgMenuApi(TokenHolder tokenHolder) {
		super(tokenHolder);
		this.ygTokenHolder = tokenHolder;
	}

	public JsonResult createMenuNew(List<WxButton> buttons) throws WeixinException {
		String menu_create_uri = getRequestUri("menu_create_uri");
		JSONObject obj = new JSONObject();
		obj.put("button", buttons);

		return createMenu0(menu_create_uri, obj);
	}

	private JsonResult createMenu0(String url, JSONObject data) throws WeixinException {
		WeixinResponse response = weixinExecutor.post(String.format(url, ygTokenHolder.getAccessToken()), JSON.toJSONString(data, new NameFilter() {
			@Override
			public String process(Object object, String name, Object value) {
				if (object instanceof Button && name.equals("content")) {
					ButtonType buttonType = ((Button) object).getType();
					if (buttonType != null) {
						if (ButtonType.view == buttonType || ButtonType.miniprogram == buttonType) {
							return "url";
						} else if (ButtonType.media_id == buttonType || ButtonType.view_limited == buttonType) {
							return "media_id";
						} else {
							return "key";
						}
					}
				}
				return name;
			}
		}));

		return response.getAsJsonResult();
	}
	public JsonResult createMenu(String jsonData) throws WeixinException {
		String menu_create_uri = getRequestUri("menu_create_uri");
		WeixinResponse response = weixinExecutor.post(String.format(menu_create_uri, ygTokenHolder.getAccessToken()),jsonData);
		

		return response.getAsJsonResult();
	}
	
}
